
var pagesize=10;
var num=1;
var operation=1;

var dataInfo={
    "username":"",
    "pageNum":1,
    "pageSize": pagesize,
    "type":"",
    "role":"",
    "state":"",
    "lock":"",
    "permission":"",
    "click":"false"         //区分用户查询操作是否需要业务日志的记录，点击搜索为ture，需要记录；上/下页为false不需要记录
};

//点击搜索
$("#secSearch").die().live("click",function () {
    $("#pageNum").text(1);
    num=1;
    var username=$("#username").val();
    var type=$("#type option:selected").val();
    var role=$("#role option:selected").val();
    var state=$("#state option:selected").val();
    var permission=$("#permission option:selected").val();
    var lock=$("#lock option:selected").val();
    //每次点击查询的都是第一页
    dataInfo={
        "username":username,
        "pageNum":1,
        "pageSize": pagesize,
        "type":type,
        "role":role,
        "state":state,
        "lock":lock,
        "permission":permission,
        "click":"true"
    };
   listSecUsers(1);
});

/**
 * 修改和删除用户之前进行弹窗校验
 * @returns {boolean}
 */
function checkDelSecUser(id,username)
{
    operation=1;
    checkUser(id,username);
}
/**
 * 子页面弹窗函数
 * @param id
 * @param username
 * @returns {boolean}
 */
function checkUser(id,username) {
    var str="checkLogin.html?id="+id+"&username="+username;

    //window.open(str,"newwindow","height=600, width=1200, toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, status=no")
    //获得窗口的垂直位置
    var iHeight=600;
    var iWidth=1200;
    var iTop = (window.screen.availHeight - 30 - iHeight) / 2;
    //获得窗口的水平位置
    var iLeft = (window.screen.availWidth - 10 - iWidth) / 2;
    window.open(str, "checklogin", 'height =600 ,width=1200 '+ ',top=' + iTop + ',left=' + iLeft + ',status=no,toolbar=no,menubar=no,location=no,resizable=no,scrollbars=0,titlebar=no');
    return false;
}

/**
 * 获取操作判别码
 * @returns {number}
 */
function getOperation() {
    return operation;
}


//账号休眠状态激活
function activeState(id) {
    isOnline("admin");
    $("#active"+id.substr(id.length-6)).attr("disabled","disabled");

    $.ajax({
        url:HOST.concat("/activesecuser?token="+config.token+"&username="+getSessionStorage("username")),
        type:"POST",
        dataType:"json",
        data:{
            "id":id
        },
        //async:false,
        success:function (res) {
            $("#active"+id.substr(id.length-6)).removeAttr("disabled");
            if(res.meta.state=="success"){
                alert("账号激活成功");
                userManagement();
            }
        },
        error:function () {
            alert("账号激活失败");
        }
    });
}

//账号锁定时解锁
function unlock(id) {
    isOnline("admin");
    $("#lock"+id.substr(id.length-6)).attr("disabled","disabled");
    $.ajax({
        url:HOST.concat("/unlocksecuser?token="+config.token+"&username="+getSessionStorage("username")),
        type:"POST",
        dataType:"json",
        data:{
            "id":id
        },
        //async:false,
        success:function (res) {
            $("#lock"+id.substr(id.length-6)).removeAttr("disabled");
            if(res.meta.state=="success"){
                alert("账号解锁成功");
                userManagement();
            }
        },
        error:function () {
            alert("账号解锁失败");
        }
    });
}

//账号授权
function givePerm(id) {
    isOnline("admin");
    $("#per"+id.substr(id.length-6)).attr("disabled","disabled");
    $.ajax({
        url:HOST.concat("/givepermissionsecuser?token="+config.token+"&username="+getSessionStorage("username")),
        type:"POST",
        dataType:"json",
        data:{
            "id":id
        },
        //async:false,
        success:function (res) {
            $("#per"+id.substr(id.length-6)).removeAttr("disabled");
            if(res.meta.state=="success"){
                alert("账号授权成功");
                userManagement();
            }
        },
        error:function () {
            alert("账号授权失败");
        }
    });
}

//移除授权
function removePerm(id) {
    isOnline("admin");
    $("#remove"+id.substr(id.length-6)).attr("disabled","disabled");
    $.ajax({
        url:HOST.concat("/removepermissionsecuser?token="+config.token+"&username="+getSessionStorage("username")),
        type:"POST",
        dataType:"json",
        data:{
            "id":id
        },
        //async:false,
        success:function (res) {
            $("#remove"+id.substr(id.length-6)).removeAttr("disabled");
            if(res.meta.state=="success"){
                alert("移除用户权限成功");
                userManagement();
            }
        },
        error:function () {
            alert("移除用户权限失败");
        }
    });
    
}

//重置用户密码
function resetUserPwd(id) {
    isOnline("admin");
    $("#reset"+id.substr(id.length-6)).attr("disabled","disabled");
    $.ajax({
        url:HOST.concat("/restsecuserpassword?token="+config.token+"&username="+getSessionStorage("username")),
        type:"POST",
        dataType:"json",
        async:false,
        data:{
            "id":id
        },
        success:function (data) {
            $("#reset"+id.substr(id.length-6)).removeAttr("disabled");
            if(data.meta.state=="success"){
                alert("密码重置成功");
            }else{
                alert(data.meta.message);
            }
        }
    });
}

//注销用户
function delSecUser(id,username) {
    var res=confirm("确认注销用户:"+username+"吗？");
    if(res){
        $("#del"+id.substr(id.length-6)).attr("disabled","disabled");
        $.ajax({
            url:HOST.concat("/removesecuser?token="+config.token+"&username="+getSessionStorage("username")),
            type:"POST",
            dataType:"json",
            async:false,
            data:{
                "id":id
            },
            success:function (data) {
                $("#del"+id.substr(id.length-6)).removeAttr("disabled");
                if(data.meta.state=="success"){
                    alert("用户注销成功");
                    userManagement();
                }
            },
            error:function () {
                alert("用户注销失败");
            }
        });
    }else{
        return ;
    }
}

//已注销用户
function delDisabled() {
    isOnline("admin");
    alert("该用户已被注销,请勿重复注销");
}

//查询用户的列表
function listSecUsers(pagenum) {
    isOnline("admin");
    if(num<1){
        return false;
    }
    dataInfo.pageNum=pagenum;
    $.ajax({
        url:HOST.concat("/listsecusers?token="+config.token),
        type:"get",
        data: dataInfo,
        dataType:"json",
        success:function (res) {
            //console.log(res);
            if(res.meta.state=="success") {
                //checkRole("admin");
                if(res.meta.message=="NoAnyData"){
                    $("#tbody").empty();
                    $("#numValue").text(0);
                    //alert("无任何符合条件的数据");
                }
                else if (res.data.resArray.length == 0) {
                    //表示没有数据
                    alert("已经是最后一页!");
                    if(num>1){
                        num--;
                    }
                } else {
                    var list = res.data.resArray;
                    $("#numValue").text(res.data.resCount);
                    $("#onlineNums").text(res.data.onlineNums);
                    $("#pageNum").text(num);
                    $("#tbody").empty();
                    for (var p in list) {
                        var item = list[p];
                        var username = item["username"];
                        var online = item["online"];
                        var role = item["role"];
                        var accessTime = item["accessTime"];
                        var createTime = item["createTime"];
                        var id = item["id"];
                        var idCard = item["idCard"];
                        var ipAddress = item["ipAddress"];
                        var lock = item["lock"];
                        var type = item["type"];
                        var permission = item["permission"];
                        var phone = item["phone"];
                        var state = item["state"];
                        var lastSleepTime = item["lastSleepTime"];

                        if (lastSleepTime==""||lastSleepTime==undefined){
                            lastSleepTime="/";
                        }

                        switch (role) {
                            case 'operator':
                                role = "业务操作员";
                                break;
                            case 'auditor':
                                role = "业务审计员";
                                break;
                            case 'sysAuditor':
                                role = "系统审计员";
                                break;
                            case 'admin':
                                role = "系统管理员";
                                break;
                        }

                        var newId = id.substr(id.length - 6);



                        if (lock == 0 || lock == "0") {
                            lock = "<div class='textContent'>未锁定</div>";
                        } else {
                            var lid = "lock" + newId;
                            lock = "<button id=" + lid + "  class=\"lockBtn\" title=\"点击解锁\" onclick='unlock(\"" + id + "\")'>已锁定</button>"
                        }

                        if(permission==1||permission=="1"){
                            permission="<div class='textContent'>未授权</div>";
                        }else if(permission==2||permission=="2"){
                            //permission="<div class='textContent' style='color: rgba(30,144,255,1)'>已授权</div>";
                            var pid="remove"+newId;
                            permission="<button id="+pid+" class=\"secBtn-green\" onclick='removePerm(\""+id+"\")' title=\"点击移除用户权限\">已授权</button>";
                        }else{
                            var pid="per"+newId;
                            permission="<button id="+pid+" class=\"secBtn-blue\" onclick='givePerm(\""+id+"\")' title=\"点击同意授权给用户\">授权用户</button>";
                        }
                        var rid="reset"+newId;
                        var restBtn="<button id="+rid+" class=\"resetPwdBtn\"  onclick='resetUserPwd(\""+id+"\")' title=\"点击重置密码\">重置</button>"

                        if (state == 0 || state == "0") {
                            state = "<div  class='textContent'>已注销</div>";
                            restBtn="<button id="+rid+" class=\"unBtn\" onclick='注销用户无法重置密码' disabled  title=\"注销用户无法重置密码\">重置</button>";
                        } else if (state == 2) {
                            state = "<div class='textContent' style='color: rgba(30,144,255,1)'>已激活</div>";
                        } else {
                            var sid = "active" + newId;
                            state = " <button id=" + sid + " class=\"secBtn-yellow\" onclick='activeState(\"" + id + "\")' title=\"点击激活\">休眠</button>";
                        }

                        var eid="edit"+newId;
                        var editArea="<a id="+eid+" href=\"#\" onclick='checkandEditSecUser(\""+id+"\")' class=\"updateUser\"><i class=\"fa fa-edit fa-lg\" title=\"查看/修改用户\"></i></a>";

                        var did="del"+newId;
                        var delArea="<a id="+did+" href=\"#\" class=\"removeUser\" onclick='checkDelSecUser(\""+id+"\",\""+username+"\")'><i class=\"fa fa-trash fa-lg\" title=\"注销该用户\"></i></a>";
                        if(item["state"]=="0"||item["state"]==0){
                            delArea="<a id="+did+" href=\"#\" class=\"removeUser\" disabled='disabled' onclick='delDisabled()'  ><i class=\"fa fa-trash fa-lg\" title=\"该用户已被注销\"></i></a>";
                        }
                        $("#tbody").append("    <div class=\"tr clearfix border-bottom-none\">" +
                            "                        <div  class=\"td w10\">" + username + "</div>" +
                            "                        <div  class=\"td w10\">" + (online == true ? '在线' : '离线') + "</div>" +
                            "                        <div  class=\"td w10\">" + role + " </div>" +
                            "                        <div  class=\"td w10\">" + (type == 0 ? '临时账号' : '永久账号') + "</div>" +
                            "                        <div  class=\"td w10\">" + state + " </div>" +
                            "                        <div  class=\"td w10\">" + lock + "</div>" +
                            "                        <div  class=\"td w10\">" +permission+"</div>" +
                            "                        <div  class=\"td w10\">"+ restBtn+ "</div>" +
                            "                        <div class=\"td w10\">"+lastSleepTime +"</div>" +
                            "                        <div class=\"td w10\">" +
                            "                            <div style=\"display: inline-block;\">"+editArea +delArea+"</div>" +
                            "                        </div>" +
                            "                    </div>");
                    }
                }
            } else if(res.meta.state=="failed"){
                if(num>1){
                    num--;
                }
                alert("已经是最后一页");
            }else{
                alert("服务器未知错误！");
                return false;
            }
        }
    });
}

//查询上一页
function lastSecUser() {
    // checkRole("admin");
    if(num<=1){
        num = 1;
        alert("已经是第一页!");
        $("#pageNum").text(num);
    }else{
        num--;
        dataInfo.click="false";
        listSecUsers(num);
    }
}

//查询下一页
function nextSecUser() {
    dataInfo.click="false";
    // checkRole("admin");
    num++;
    listSecUsers(num);
}

//查询首页
function listFirstSecUsers() {
    // checkRole("admin");
    if(num==1){
        alert("已经是第一页");
    }else {
        num=1;
        $("#pageNum").text(num);
        dataInfo.click="false";
        listSecUsers(num);
    }

}

//重置
$("#secReset").live("click",function () {
    // checkRole("admin");
    $("#username").val("");
    $("#role option:first").prop("selected", 'selected');
    $("#type option:first").prop("selected", 'selected');
    $("#state option:first").prop("selected", 'selected');
    $("#lock option:first").prop("selected", 'selected');
    $("#permission option:first").prop("selected", 'selected');

});

